import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import { allRoutes } from '@/router'

function filterPermissionsRouters(routes: Array<RouteRecordRaw>, roles: Array<unknown>) {
  const res: Array<RouteRecordRaw> = []
  const removeRoutes: Array<RouteRecordRaw> = []
  routes.forEach(route => {
    const children: Array<RouteRecordRaw> = []
    route.children?.forEach(childRouter => {
      const roleCode = childRouter.name
      // debugger
      if (roles.indexOf(roleCode) !== -1) {
        if(childRouter.children && childRouter.children.length > 0){
          childRouter.children.forEach((item, index) => {
            if(item.meta!.hidden == true){
              childRouter.children!.splice(index, 1)
            }
          })
        }
        children.push(childRouter)
      } else {
        removeRoutes.push(childRouter)
      }
    })
    if (children.length > 0) {
      route.children = children
      res.push(route)
    }
  })
  return { accessedRouters: res, removeRoutes }
}

let routers: Array<RouteRecordRaw> = []
export const usePermissionStore = defineStore('permission', {
  state: () => ({
    whiteListRouters: ['/login'],
    routers,
  }),

  actions: {
    async initRoutes(roles: Array<unknown>) {
      let accessedRouters = []
      let removeRoutes: Array<RouteRecordRaw> = []
      if (roles.includes('all')) {


        accessedRouters = allRoutes
      } else {
        const res = filterPermissionsRouters(allRoutes, roles)
        accessedRouters = res.accessedRouters
        removeRoutes = res.removeRoutes
      }

      this.routers = accessedRouters
    },
  },
})
